package org.example.leetcode.addon.lc40;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Solution {
    List<List<Integer>> ans = new LinkedList<>();
    Deque<Integer> condition = new LinkedList<>();
    boolean[] used;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        used = new boolean[candidates.length];
        Arrays.fill(used, false);
        Arrays.sort(candidates);

        backtracking(candidates, target, 0, 0);

        return ans;
    }

    private void backtracking(int[] candidates, int target, int sum, int startIndex) {
        if (sum > target) {
            return ;
        }
        if (sum == target) {
            ans.add(new LinkedList<>(condition));
            return ;
        }

        for (int i = startIndex; i < candidates.length; i++) {
            if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) {
                continue;
            }
            used[i] = true;
            sum += candidates[i];
            condition.add(candidates[i]);
            backtracking(candidates, target, sum, i + 1);
            used[i] = false;
            sum -= candidates[i];
            condition.removeLast();
        }
    }
}
